package com.psq.core.common.model

import com.psq.core.common.utils.toTypeString


typealias Success<T> = (T?) -> Unit
typealias Failure = (String, String) -> Unit

open class ApiResponse<T>(
    val data: T? = null,
    val errorCode: String = "",
    val errorMessage: String = "",
    val status: String = ""
)  {
    companion object {
        const val SUCCEED = "SUCCEED"
        const val FAILED = "FAILED"
    }

    override fun toString(): String {
        return toTypeString()
    }

    class Error<T>(errorMessage: String) : ApiResponse<T>(null, "", errorMessage, FAILED)
}

fun <T> ApiResponse<T>.whenSuccess(success: Success<T>): ApiResponse<T> {
    if (ApiResponse.SUCCEED == status) {
        success(this.data)
    }
    return this
}

fun <T> ApiResponse<T>.whenFailure(failure: Failure): ApiResponse<T> {
    if (ApiResponse.FAILED == status) {
        failure(this.errorCode, this.errorMessage)
    }
    return this
}

fun <T> ApiResponse<T>.`do`(
    success: Success<T>,
    failure: Failure = { _, _ -> }
): ApiResponse<T> {
    whenSuccess(success)
    whenFailure(failure)
    return this
}